<?php

namespace Xrfg\Wallet\TRX\Console;

use Exception;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\Coin;
use App\Models\Recharge as RechargeModel;
use App\Models\Account;
use App\Models\Wtrx;
use Xrfg\Wallet\Common\Jobs\RechargeJob;
use Xrfg\Wallet\TRX\Services\TRXWallet;
use Xrfg\Wallet\TRX\Traits\TRXHelper;
use Xrfg\Core\Trading\Account\Models\Account as TraddingAccount;

class RechargeTRC20 extends Command
{
    use TRXHelper;

    protected $signature = 'recharge:trc20 {coin_name}';

    protected $description = 'TRC20 充值';

    protected $times = 0;

    public $http;

    protected $rpc;

    protected $blockNumber;

    public function __construct()
    {
        parent::__construct();
        $this->http = new Client();

        $this->rpc = new TRXWallet(config('wallet.trx.node.wallet'));
    }

    public function handle()
    {
        $coin_name = strtoupper($this->argument('coin_name'));
        $coin = Coin::where('name', $coin_name)->first();
        if (!$coin) {
            return;
        }
        // 合约地址
        $contract_address = config("wallet.trx.contracts.{$coin_name}.contractAddress");
        // 合约小数位
        $decimals = config("wallet.trx.contracts.{$coin_name}.decimals");

        ++$this->times;
        if ($this->times >= 100) {
            return;
        }
        $this->info('times:'.$this->times);
        $this->blockNumber = Cache::get('TRC20:blockNumber', 24127942); // 24379156没有数据，24127943有数据
        sleep(1);
        try {
            $result = $this->rpc->getCurrentBlock();
            $blockNumber = $result['block_header']['raw_data']['number'];
            $this->info("latest:{$blockNumber}");
            if ($blockNumber - 3 <= $this->blockNumber) {
                self::handle();

                return;
            }
            $this->info('current:'.$this->blockNumber);
            $this->info('scanning:'.($this->blockNumber + 1));
            $scanningNumber = $this->blockNumber + 1;
            $result = $this->rpc->getBlockByNumber($scanningNumber);
            if (!empty($result['transactions'])) {
                $data = $result['transactions'];
                if(count($data) >0){
                    foreach ($data as $tx) {
                        if($tx['raw_data']['contract'][0]['type'] == 'TriggerSmartContract' && $tx['ret'][0]['contractRet'] == 'SUCCESS') {
                            $hex_add = $tx['raw_data']['contract'][0]['parameter']['value']['contract_address'];
                            $con_data = $tx['raw_data']['contract'][0]['parameter']['value']['data'];
                            $contract_address_com = $this->rpc->hexString2Address($hex_add);
                            if ($contract_address_com == $contract_address) {
                                $hex_address =  '41' . substr($con_data, 32, 40);
                                $wtrx = Wtrx::where('hex_address', $hex_address)->first();
                                if ($wtrx) { // 过滤自己的地址
                                    // USDT的TRC20充币
                                    // 以太星球地址
                                    $isAccountExists = Account::where('coin_id', $coin->id)
                                        ->where('address', $wtrx->address)
                                        ->exists();
                                    // 交易所地址
                                    $isTraddingAccountExists = TraddingAccount::where('coin_id', $coin->id)
                                        ->where('address', $wtrx->address)
                                        ->exists();
                                    if ($isAccountExists || $isTraddingAccountExists) {
                                        $coinId = $coin->id;
                                        $hash = $tx['txID'];
                                        $address = $wtrx->address;
                                        $number = hexdec(substr($con_data, 74))/pow(10,$decimals);
                                        logger([$hash, $number, $wtrx->address]);

                                        $isRechargeExists = RechargeModel::where('hash', $hash)->exists();
                                        // 检查hash
                                        if (!$isRechargeExists) {
                                            RechargeJob::dispatch($coinId, $hash, $number, $address)
                                                ->onQueue('recharge');
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
            // 方案一：已弃用
//            $response = $this->http->get("https://api.trongrid.io/v1/blocks/{$scanningNumber}/events", ['verify' => false]);
//            $data = (json_decode($response->getBody()->getContents(), true))['data'];
//            if ($data) {
//                foreach ($data as $tx) {
//                    if ($contract_address == $tx['contract_address']) { // 过滤TRC20合约转账
//                        if (isset($tx['result']['to'])) {
//                            $hex_address = '41'.substr($tx['result']['to'], 2, 40);
//                            $wtrx = Wtrx::where('hex_address', $hex_address)->first();
//                            if ($wtrx) { // 过滤自己的地址
//                                // USDT的TRC20充币
//                                $isAccountExists = Account::where('coin_id', $coin->id)
//                                    ->where('address', $wtrx->address)
//                                    ->exists();
//                                if ($isAccountExists) {
//                                    $coinId = $coin->id;
//                                    $hash = $tx['transaction_id'];
//                                    $address = $wtrx->address;
//                                    $number = $tx['result']['value'] /  pow(10, $decimals);
//
//                                    $isRechargeExists = RechargeModel::where('hash', $hash)->exists();
//                                    // 检查hash
//                                    if (!$isRechargeExists) {
//                                        RechargeJob::dispatch($coinId, $hash, $number, $address)
//                                            ->onQueue('recharge');
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//                Cache::forever('TRC20:blockNumber', $this->blockNumber + 1);
//            }
            Cache::forever('TRC20:blockNumber', $this->blockNumber + 1);
            self::handle();
        } catch (Exception $exception) {
            Log::error($exception);
            self::handle();
        }
    }
}
